<?php

namespace App\Jobs\Pay;

use App\Models\Trip\TripOrderRefund\TripOrderRefund;
use App\Trip\Wechat\Pay\RefundRes\RefundResult;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class ProcessWechatRefundCallback implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $uniqueFor = 60;

    private RefundResult $refundResult;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(RefundResult $refundResult)
    {
        $this->refundResult = $refundResult;
    }

    /**
     * Execute the job.
     *
     * @return void
     * @throws Exception
     */
    public function handle()
    {
        $refund = new TripOrderRefund();
        if ($this->refundResult->isSuccess()) {
            $refund->refundSuccess($this->refundResult);
        } else {
            // 需要记录失败次数
            $refund->refundFailedAndRetry($this->refundResult);
        }
    }


    /**
     * 任务的唯一 ID。
     *
     * @return string
     */
    public function uniqueId()
    {
        return $this->refundResult->getOutTradeNo();
    }

    public function failed()
    {
        $pay_sn = $this->refundResult->getOutTradeNo();
        Log::error("退款单号回调业务处理失败：{$pay_sn}");
    }

    /**
     * 计算重试任务之前要等待的秒数。
     *
     * @return array
     */
    public function backoff()
    {
        return TripOrderRefund::REFUND_FAILED_BACKOFF;
    }
}
